package order;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import java.util.List;

/**
 * @Author if
 * @Description: 顺序消息生产者
 * @Date 2021-10-24 下午 08:25
 */
public class OrderedProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        DefaultMQProducer producer=new DefaultMQProducer("pg");
        producer.setNamesrvAddr("centos:9876");
        producer.start();
        for(int i=0;i<100;i++){
            //oderId表示订单id
            int orderId=i;
            byte[] body=("Hi,"+i).getBytes();
            Message msg=new Message("OrderedTopic","OrderedTag",body);
            //将oderId当做消息key并充当选择算法中的选择key
            msg.setKeys(orderId+"");
            //send()方法的第三个参数Object arg我们这使用业务id，即订单id
            //这个arg会传递给选择器
            //该send为同步发送，当然也可以加一个SendCallback将其变为异步发送
            SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                //订单选择器的选择算法
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    //以下是使用消息key作为选择key的选择算法
                    String key=message.getKeys();
                    int id=Integer.parseInt(key);

                    //以下是使用arg作为选择key
//                    int id=(int) o;

                    int index=id % list.size();
                    return list.get(index);
                }
            },orderId);
            System.out.println(sendResult);
        }
        producer.shutdown();
    }
}
